<template>
  <div class="permission_container">
    <div class="top_container">
      <div class="back_arrow">
        <van-icon name="arrow-left" size="0.6rem" @click="back()" />
      </div>
      <div class="top_title_container">
        <div class="title">{{ currentTitle }}</div>
      </div>
    </div>
    <div class="content_container">
      <!-- 模板图标  -->
      <div class="content_box" style="margin-top: 0">
        <div class="content_item">
          <div class="item_label">模板图标</div>
          <div class="item_icon" @click="showIconDrage()">
            <div class="icon_text">
              <van-icon
                class="iconfont"
                class-prefix="icon"
                :name="currentIcon.icon"
                :color="currentIcon.color"
                size="0.7rem"
              />
            </div>
            <van-icon
              name="arrow"
              size="0.4rem"
              color="#dedede"
              style="font-weight: bold"
            />
          </div>
        </div>
      </div>
      <!-- 填写人 -->
      <div class="content_box">
        <div class="content_item">
          <div class="item_label">
            <div class="star">*</div>
            填写人
          </div>
          <div class="item_icon" @click="scopeHandle()">
            <div class="icon">{{ scopeText }}</div>
            <van-icon
              name="arrow-down"
              size="0.4rem"
              color="#dedede"
              style="font-weight: bold"
            />
          </div>
        </div>
      </div>
      <!-- 填写人 -->
      <div class="member_container" v-if="scopeRadio == 2">
        <div
          class="member_li"
          v-for="(item, index) in appointFor"
          :key="index"
          @click="addWritter()"
        >
          <img :src="item.img" alt="" @click="addWritter()" />
          <div class="name">{{ item.userName }}</div>
        </div>
        <div class="member_li">
          <van-icon
            name="add-o"
            size="0.8rem"
            color="#878787"
            @click="addWritter()"
          />
          <div class="name">添加填写人</div>
        </div>
      </div>
      <div class="content_box">
        <div class="content_item">
          <div class="item_label">填写字数限制</div>
          <div class="item_icon">
            <van-switch
              v-model="textLimit"
              size="0.6rem"
              @change="limitHandle"
            />
          </div>
        </div>
        <div class="content_item" v-if="textLimit">
          <div class="item_label">最少可输入</div>
          <div class="item_icon">
            <van-field
              v-model="minWord"
              input-align="right"
              type="digit"
              placeholder="最少可输入"
            />
          </div>
        </div>
        <div class="content_item" v-if="textLimit">
          <div class="item_label">最多可输入</div>
          <div class="item_icon">
            <van-field
              v-model="maxWord"
              input-align="right"
              type="digit"
              placeholder="不填写则不限制字数"
              @blur="maxBlur()"
            />
          </div>
        </div>
      </div>
      <!-- 是否允许修改 -->
      <div class="content_box">
        <div class="content_item">
          <div class="item_label">填写后不允许修改</div>
          <div class="item_icon">
            <van-switch v-model="isModify" size="0.6rem" />
          </div>
        </div>
      </div>
      <!-- 发送人 -->
      <div class="content_box">
        <div class="content_item">
          <div class="item_label">
            <div class="star">*</div>
            默认发送人
          </div>
        </div>
      </div>
      <div class="member_container">
        <div
          class="member_li"
          v-for="(item, index) in defaultFor"
          :key="index"
          @click="addSendUser()"
        >
          <img :src="item.img" alt="" />
          <div class="name">{{ item.userName }}</div>
        </div>
        <div class="member_li">
          <van-icon
            name="add-o"
            size="0.8rem"
            color="#878787"
            @click="addSendUser()"
          />
          <div class="name">添加发送人</div>
        </div>
      </div>
      <!-- 自定义发送人 -->
      <div class="content_box" style="margin-top: 0">
        <div class="content_item">
          <div class="item_label">允许自定义添加发送人</div>
          <div class="item_icon">
            <van-switch v-model="isSend" size="0.6rem" />
          </div>
        </div>
      </div>
    </div>
    <div class="bottom_container">
      <div class="btn_item" style="width: 100%">
        <div class="btn" @click="createHandle()" v-if="!currentId">创建</div>
        <div class="btn" @click="createHandle()" v-else>保存</div>
      </div>
    </div>

    <!-- 填写范围 -->
    <van-popup v-model:show="scopeFlag" round>
      <van-radio-group v-model="scopeRadio" @change="scopeChange()">
        <van-radio
          :name="item.value"
          v-for="(item, index) in scopeList"
          :key="index"
          >{{ item.label }}</van-radio
        >
      </van-radio-group>
    </van-popup>

    <!-- 模板图标 -->
    <van-popup v-model:show="iconFlag" round>
      <div class="icon_container">
        <div class="preview">
          <van-icon
            class="iconfont"
            class-prefix="icon"
            :name="currentIcon.icon"
            :color="currentIcon.color"
            size="1rem"
          />
        </div>
        <div class="icon_list">
          <div
            class="icon_li"
            v-for="(item, index) in iconList"
            :key="index"
            @click="iconHandle(item, index)"
          >
            <van-icon
              class="iconfont"
              class-prefix="icon"
              :name="item.icon"
              :color="item.color"
              size="0.8rem"
            />
            <div class="active" v-if="currentIconIndex == index">
              <van-icon
                class="iconfont"
                class-prefix="icon"
                name="choose"
                color="green"
                size="0.2rem"
              />
            </div>
          </div>
        </div>
      </div>
    </van-popup>

    <!-- 填写人弹窗 -->
    <VanDialog
      v-model:show="appointFlag"
      :closeOnClickOverlay="false"
      :showConfirmButton="false"
      title="深圳市斯贝达电子有限公司"
    >
      <SelectUser @submitUser="setAppointForUser" :list="appointFor" />
    </VanDialog>

    <!-- 发送人弹窗 -->
    <VanDialog
      v-model:show="defaultFlag"
      :closeOnClickOverlay="false"
      :showConfirmButton="false"
      title="深圳市斯贝达电子有限公司"
    >
      <SelectUser @submitUser="setDefaultForUser" :list="defaultFor" />
    </VanDialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { Toast } from "vant";
import SelectUser from "@/components/selectUser.vue";
import { AddTemplate, UpdateTemplate, GetTemplateInfo } from "@/api/log";
onMounted(() => {
  if (localStorage.getItem("localPermissLog")) {
    localPermissLog.value = JSON.parse(localStorage.getItem("localPermissLog"));
    //缓存数据回显
    currentIcon.value = localPermissLog.value.currentIcon;
    scopeRadio.value = localPermissLog.value.scopeRadio;
    textLimit.value = localPermissLog.value.textLimit;
    maxWord.value = localPermissLog.value.maxWord;
    minWord.value = localPermissLog.value.minWord;
    isModify.value = localPermissLog.value.isModify;
    isSend.value = localPermissLog.value.isSend;
    appointFor.value = localPermissLog.value.appointFor;
    defaultFor.value = localPermissLog.value.defaultFor;
  } else {
    getInfo();
  }

  if (scopeRadio.value == 1) {
    scopeText.value = "组织内成员均可以填写";
  } else {
    scopeText.value = "组织内指定的成员可以填写";
  }
});
//上一页缓存的数据
const logItem = JSON.parse(localStorage.getItem("tempLog"));
const localPermissLog = ref({});

const fields = ref([]);
fields.value = logItem.fields.map((item) => {
  return {
    Type: item.Type,
    Key: item.Key,
    PromptText: item.PromptText,
    State: item.State,
    Value: item.Value.map((it) => {
      return it.name;
    }).join(","),
  };
});
const currentTitle = ref("");
const currentId = ref(null);
const route = useRoute();
const router = useRouter();
currentId.value = Number(route.query.id);
const getInfo = async () => {
  if (currentId.value) {
    const res = await GetTemplateInfo({ id: currentId.value });
    if (res.code == 200) {
      currentIcon.value = res.data.logImg;
      minWord.value = res.data.minWord;
      maxWord.value = res.data.maxWord;
      isModify.value = res.data.isModify;
      isSend.value = res.data.isSend;
      appointFor.value = res.data.appointFor;
      defaultFor.value = res.data.defaultFor;
      if (maxWord.value) {
        textLimit.value = true;
      }
      if (appointFor.value) {
        scopeRadio.value = 2;
        scopeText.value = "组织内指定成员可以填写";
      } else {
        scopeRadio.value = 1;
        scopeText.value = "组织内成员均可以填写";
      }
    }
  }
};
//返回上一步
const back = async () => {
  let localPermissLogObj = {
    currentIcon: currentIcon.value,
    scopeRadio: scopeRadio.value,
    textLimit: textLimit.value,
    maxWord: maxWord.value,
    minWord: minWord.value,
    isModify: isModify.value,
    isSend: isSend.value,
    appointFor: appointFor.value,
    defaultFor: defaultFor.value,
  };
  localStorage.setItem("localPermissLog", JSON.stringify(localPermissLogObj));
  router.go(-1);
};
currentTitle.value = route.meta.title;
const textLimit = ref(false);
const isModify = ref(false);
const isSend = ref(false);
const minWord = ref(1);
const maxWord = ref("");
const scopeFlag = ref(false);
const iconFlag = ref(false);
const showIconDrage = () => {
  iconFlag.value = true;
};
const iconList = ref([
  {
    icon: "bianji3",
    color: "#4291e0",
  },
  {
    icon: "worklog",
    color: "#4291e0",
  },
  {
    icon: "ribao",
    color: "#68e261",
  },
  {
    icon: "yuebao",
    color: "#69b3fa",
  },
  {
    icon: "zhoubao",
    color: "#fb7676",
  },
  {
    icon: "jieshou",
    color: "#a971eb",
  },
  {
    icon: "tuifei",
    color: "#eab639",
  },
  {
    icon: "danju",
    color: "#40bed3",
  },
  {
    icon: "shuju",
    color: "#4291e0",
  },
  {
    icon: "jiaofei",
    color: "#eab639",
  },
  {
    icon: "tuandui",
    color: "#40bed3",
  },
  {
    icon: "fuhe",
    color: "#4291e0",
  },
  {
    icon: "baogao",
    color: "#36c7a4",
  },
  {
    icon: "dayin",
    color: "#36c7a4",
  },
  {
    icon: "pizhun",
    color: "#f46c6c",
  },
  {
    icon: "shenhe",
    color: "#4291e0",
  },
  {
    icon: "gaizhang",
    color: "#f46c6c",
  },
  {
    icon: "shouye",
    color: "#4291e0",
  },
  {
    icon: "rili",
    color: "#a971eb",
  },
  {
    icon: "dangan",
    color: "#eab639",
  },
  {
    icon: "yingyong",
    color: "#a971eb",
  },
  {
    icon: "gonggao",
    color: "#f46c6c",
  },
  {
    icon: "tongji",
    color: "#4291e0",
  },
]);
const currentIcon = ref({
  icon: "bianji3",
  color: "#4291e0",
});
const currentIconIndex = ref(0);
//选择图标
const iconHandle = (item, index) => {
  currentIcon.value = item;
  currentIconIndex.value = index;
};
const scopeText = ref("组织内的成员均可以填写");
const appointFor = ref(null);
const appointFlag = ref(false);
const defaultFlag = ref(false);
const defaultFor = ref([]);
const scopeHandle = () => {
  scopeFlag.value = true;
};
const scopeList = ref([
  {
    label: "组织内的成员均可以填写",
    value: 1,
  },
  {
    label: "组织内指定的成员可以填写",
    value: 2,
  },
]);
const scopeRadio = ref(1);
//切换填写人范围
const scopeChange = () => {
  scopeList.value.forEach((item) => {
    if (item.value == scopeRadio.value) {
      scopeText.value = item.label;
      return;
    }
  });
  if (scopeRadio.value == 1) {
    appointFor.value = null;
  }
  scopeFlag.value = false;
};
//字数限制开关
const limitHandle = (val) => {
  if (!val) {
    maxWord.value = "";
    minWord.value = 1;
  }
};
//最多字数校验
const maxBlur = () => {
  if (Number(maxWord.value) < Number(minWord.value)) {
    maxWord.value = "";
  }
};
//填写人/发送人判断
const userTab = ref(0);
//新增发送人
const addSendUser = () => {
  userTab.value = 2;
  defaultFlag.value = true;
};
//新增填写人
const addWritter = () => {
  userTab.value = 1;
  appointFlag.value = true;
};

//发送人
const setDefaultForUser = (val) => {
  defaultFor.value = val.map((item) => {
    return { userId: item.id, userName: item.label, img: item.img, lock: true };
  });
  defaultFlag.value = false;
};
//填写人
const setAppointForUser = (val) => {
  appointFor.value = val.map((item) => {
    return { userId: item.id, userName: item.label, img: item.img };
  });
  appointFlag.value = false;
};
let submitFlag = ref(true);
//创建
const createHandle = async () => {
  if (submitFlag.value) {
    if (scopeRadio.value == 2 && !appointFor.value) {
      return Toast.fail("填写人不能为空");
    }
    if (!defaultFor.value.length) {
      return Toast.fail("发送人不能为空");
    }
    submitFlag.value = false;
    let temp = {
      name: logItem.name,
      fields: fields.value,
      logImg: currentIcon.value,
      defaultFor: defaultFor.value ? defaultFor.value : null,
      appointFor: appointFor.value ? appointFor.value : null,
      maxWord: maxWord.value ? Number(maxWord.value) : null,
      minWord: minWord.value ? Number(minWord.value) : 1,
      isModify: isModify.value,
      isSend: isSend.value,
    };
    console.log("temp", temp);
    let req = {};
    if (currentId.value) {
      req = { ...temp, id: currentId.value };
      console.log("req", req);
      const res = await UpdateTemplate(req);
      if (res.code == 200) {
        localStorage.setItem("tempLog", "");
        localStorage.setItem("localPermissLog", "");
        Toast.success("编辑成功");
        setTimeout(() => {
          submitFlag.value = true;
          router.push("log");
        }, 1000);
      } else {
        submitFlag.value = true;
      }
    } else {
      req = temp;
      const res = await AddTemplate(req);
      if (res.code == 200) {
        localStorage.setItem("tempLog", "");
        localStorage.setItem("localPermissLog", "");
        Toast.success("创建成功");
        setTimeout(() => {
          submitFlag.value = true;
          router.push("log");
        }, 1000);
      }else{
        submitFlag.value = true;
      }
    }
  }
};
</script>
<style lang="scss" scoped>
@import "../base.scss";
.permission_container {
  width: 100%;
  height: 100vh;
  position: relative;
  padding: 40px 0;
  box-sizing: border-box;

  .content_box {
    width: 100%;
    margin-top: 20px;
    background-color: #fff;
    .content_item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 10px 10px 10px 5px;
      box-sizing: border-box;
      border-bottom: 2px solid #f8f8f8;
      position: relative;
      .item_label {
        font-size: 0.5rem;
        display: flex;
        margin-left: 8px;
        .star {
          color: red;
          margin-top: 3px;
          position: absolute;
          left: 2px;
          font-size: 0.6rem;
        }
      }
      .item_icon {
        font-size: 0.3rem;
        display: flex;
        align-items: center;
        cursor: pointer;
        .icon {
          margin-right: 10px;
          color: #a2a2a2;
        }
        .icon_text {
          width: 0.7rem;
          height: 0.7rem;
          display: flex;
          justify-content: center;
          align-items: center;
          margin-right: 10px;
        }
        .text {
          font-size: 0.3rem;
          color: #b0b0b0;
          margin-right: 10px;
        }
      }
    }
    .manager_container {
      display: flex;
      flex-wrap: wrap;
      align-items: center;
      background-color: #fff;
      padding-left: 20px;
      padding-bottom: 20px;
      box-sizing: border-box;
      .manage_li {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        margin-right: 20px;
        margin-bottom: 20px;
        img {
          width: 1rem;
          height: 1rem;
          border-radius: 5px;
          background-size: cover;
        }
        .van-icon {
          width: 1rem;
          height: 1rem;
          display: flex;
          justify-content: center;
          align-items: center;
        }
        .name {
          font-size: 0.3rem;
          color: #a8a8ac;
          margin-top: 4px;
        }
      }
    }
  }
  .member_container {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    background-color: #fff;
    padding-left: 20px;
    padding-top: 10px;
    box-sizing: border-box;
    .member_li {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      margin-right: 20px;
      margin-bottom: 10px;
      cursor: pointer;
      img {
        width: 1rem;
        height: 1rem;
        border-radius: 5px;
        background-size: cover;
      }
      .van-icon {
        width: 1rem;
        height: 1rem;
        display: flex;
        justify-content: center;
        align-items: center;
      }
      .name {
        min-height: 20px;
        font-size: 0.3rem;
        color: #a8a8ac;
        margin-top: 4px;
      }
    }
  }
  :deep(.van-popup--center) {
    width: 90%;
    padding: 20px;
    box-sizing: border-box;
  }
  :deep(.van-dialog) {
    width: 90%;
    padding: 0px;
    box-sizing: border-box;
  }
  :deep(.van-radio-group) {
    font-size: 0.35rem;
    .van-radio {
      margin: 10px 0;
    }
  }
  .icon_container {
    .preview {
      width: 1.2rem;
      height: 1.2rem;
      margin: 0 auto;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .icon_list {
      margin-top: 10px;
      display: flex;
      flex-wrap: wrap;
      align-items: center;
      .icon_li {
        width: 1rem;
        height: 1rem;
        margin: 5px;
        display: flex;
        justify-content: center;
        align-items: center;
        position: relative;
        .active {
          width: 0.3rem;
          height: 0.3rem;
          position: absolute;
          display: flex;
          justify-content: center;
          align-items: center;
          bottom: 0px;
          right: 0;
          z-index: 99;
          background-color: #fff;
          border-radius: 50%;
        }
      }
    }
  }
}
</style>
